package com.xbh.management.security;

import com.xbh.management.entity.ManUserVO;
import com.xbh.management.model.ManRole;
import com.xbh.management.model.ManUser;
import com.xbh.management.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * @program: management-center
 * @description: 访问决策管理器
 * @author: 许宝华
 * @create: 2021-12-06 11:40
 */

@Component
public class UserAccessDecisionManager implements AccessDecisionManager {

    private static Logger log = LoggerFactory.getLogger(UserAccessDecisionManager.class);

    @Autowired
    private UserService userService;
    /**
     * 先查询此用户当前拥有的权限，然后与上面过滤器核查出来的权限列表作对比，
     * 以此判断此用户是否具有这个访问权限，决定去留！所以顾名思义为权限决策器。
     * @param authentication
     * @param object
     * @param configAttributes
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {


        Iterator<ConfigAttribute> iterator = configAttributes.iterator();
        while (iterator.hasNext()) {
            if (authentication == null) {
                throw new AccessDeniedException("当前访问没有权限");
            }
            ConfigAttribute ca = iterator.next();
            //当前请求需要的权限
            String needRole = ca.getAttribute();
            if ("ROLE_LOGIN".equals(needRole)) {
                if (authentication instanceof AnonymousAuthenticationToken) {
                    log.info("未登录");
                    throw new BadCredentialsException("未登录");
                }
                log.info("默认角色，没有权限");
                throw new AccessDeniedException("权限不足!");
            }
            //当前用户所具有的权限
            ManUser user = new ManUser();
            String username = authentication.getPrincipal().toString();
            user.setUsername(username);
            ManUserVO manUserVO = userService.queryUserRelationAllRoleByUsername(user);
            List<ManRole> roleList = manUserVO.getRoleList();
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (ManRole roleName : roleList) {
                if (roleName.getRoleName().equals(needRole)) {
                    return;
                }
            }
        }
        log.info("权限不足!");
        throw new AccessDeniedException("权限不足!");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
